<template>
  <!-- 新增项目 -->
  <el-dialog destroy-on-close :modal-append-to-body="false" :title="addFormInline.project_id ? '项目完善' : '新增项目'"
    :visible.sync="addShow" width="1000px" :close-on-click-modal="false" @close="cancelFunc">
    <div class="scroll-view">
      <el-form :rules="addRules" ref="addRuleForm" :model="addFormInline" class="demo-form-inline" :inline="true"
        label-position="left">
        <el-form-item label="项目名称" prop="project_name">
          <el-input clearable placeholder="输入项目名称" class="input-box" v-model="addFormInline.project_name"></el-input>
        </el-form-item>
        <el-form-item label="所属地区" prop="project_city">
          <el-cascader class="input-box" v-model="addFormInline.project_city" :options="cityList" placeholder="请选择所属地区"
            clearable :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input clearable placeholder="输入详细地址" class="input-box" v-model="addFormInline.address"></el-input>
        </el-form-item>
        <el-form-item label="客户经理" prop="account_manager_id" v-if="userInfo.position_id != 2" :rules="[
          { required: true, message: '请选择客户经理', trigger: 'change' },
        ]">
          <el-select filterable @change="selectChangeFunc({ $event, type: 'account_manager_id' })" clearable class="input-box"
            v-model="addFormInline.account_manager_id" placeholder="请选择收款账户">
            <el-option v-for="item in accountManagerAdminList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款账户" prop="receiving_account_id">
          <el-select filterable @change="selectChangeFunc({ $event, type: 'receiving_account_id' })" clearable class="input-box"
            v-model="addFormInline.receiving_account_id" placeholder="请选择收款账户">
            <el-option v-for="item in receivingAccountList" :key="item.id" :label="item.account_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联客户" prop="user_id">
          <el-select filterable :disabled="addFormInline.source == 3" @change="selectChangeFunc({ $event, type: 'user' })"
            clearable class="input-box" v-model="addFormInline.user_id" placeholder="请选择客户">
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌经理" prop="channel_manager_id">
          <el-select filterable @change="selectChangeFunc({ $event, type: 'channel_manager' })" clearable class="input-box"
            v-model="addFormInline.channel_manager_id" placeholder="请选择品牌经理">
            <el-option v-for="item in channelManagerList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand_id">
          <el-select filterable :disabled="detailData.status == 1102 || detailData.status > 1102"
            @change="selectChangeFunc({ $event, type: 'brand' })" clearable class="input-box"
            v-model="addFormInline.brand_id" placeholder="请选择品牌">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户需求品牌" v-if="otherBrand">
          <el-input clearable disabled class="input-box" v-model="otherBrand"></el-input>
          <span @click="goToAddBrankFunc" class="brank-tips">去添加品牌<i class="el-icon-arrow-right"></i></span>
        </el-form-item>
        <el-form-item label="装修类型" prop="store_template_id" v-if="addFormInline.brand_id">
          <div class="radio-group">
            <el-select filterable :disabled="detailData.status == 1102 || detailData.status > 1102"
              @change="selectChangeFunc({ $event, type: 'store_type_name' })" clearable class="input-box"
              v-model="addFormInline.store_template_id" placeholder="请选择装修类型">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in projectTypeList"
                :key="index"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="验收模板" prop="template_id" v-if="addFormInline.brand_id">
          <el-input readonly clearable placeholder="验收模板" class="input-box"
            v-model="addFormInline.template_name" :disabled="detailData.status == 1102 || detailData.status > 1102"></el-input>
        </el-form-item>
        <el-form-item label="是否能提交进场" prop="construction_type">
          <el-radio-group v-model="addFormInline.construction_type">
            <el-radio :label="2">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否勘场" prop="survey_site">
          <el-radio-group v-model="addFormInline.survey_site" :disabled="detailData.status > 1010">
            <el-radio :label="1">无需勘场</el-radio>
            <el-radio :label="2">实地勘场</el-radio>
            <el-radio :label="3">勘场出图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="约定勘场日期" prop="survey_date" v-if="addFormInline.survey_site != 1">
          <el-date-picker :disabled="detailData.status > 1010" value-format="yyyy-MM-dd" clearable class="input-box"
            v-model="addFormInline.survey_date" type="date" placeholder="选择约定勘场日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="设计师" prop="designer_id" v-if="addFormInline.survey_site != 1">
          <el-select filterable :disabled="detailData.status > 1010" @change="selectChangeFunc({ $event, type: 'designer' })"
            clearable class="input-box" v-model="addFormInline.designer_id" placeholder="请选择设计师">
            <el-option v-for="item in designerList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="addLoading" type="primary" @click="addSubmit('addRuleForm')">提交</el-button>
      <el-button :loading="addLoading" @click="cancelFunc">关闭</el-button>
    </span>
  </el-dialog>
</template>
<script>
import adminApi from "@/api/adminApi";
import projectApi from "@/api/projectApi";
import commonApi from "@/api/common";
import brandApi from "@/api/brandApi";
import companyApi from "@/api/companyApi";
import store from "@/store";
import { getUserInfo } from '@/utils/auth';
export default {
  name: "",
  props: {
    addData: {
      type: Object,
      default: () => {
        return {
          store_template_id: "",
          store_type_name: "",
          project_name: "",
          project_city: [],
          address: "",
          user_id: "",
          channel_manager_id: "",
          brand_id: "",
          survey_site: 1,
          designer_id: "",
          template_id: "",
          survey_date: "",
        };
      },
      required: false,
    },
    addDialogVisible: {
      type: Boolean,
      default: false,
      required: false,
    },
    // 勘场信息是否能修改
    surveySiteDisabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    detailData: {
      required: false,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      userInfo: {},
      addFormInline: {
        store_template_id: "",
        store_type_name: "",
        project_name: "",
        project_city: [],
        address: "",
        user_id: "",
        channel_manager_id: "",
        brand_id: "",
        survey_site: 1,
        designer_id: "",
        template_id: "",
        survey_date: "",
        receiving_account_id: "",
        construction_type: 1,
      },
      addRules: {
        receiving_account_id: [
          {
            required: true,
            message: "请选择收款账户",
            trigger: "change",
          },
        ],
        store_template_id: [
          {
            required: true,
            message: "请选择装修类型",
            trigger: "change",
          },
        ],
        project_name: [
          {
            required: true,
            message: "请填写项目名称",
            trigger: "change",
          },
        ],
        project_city: [
          {
            required: true,
            message: "请选择所属地区",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请填写详细地址",
            trigger: "change",
          },
        ],
        user_id: [
          {
            required: true,
            message: "请选择关联客户",
            trigger: "change",
          },
        ],
        channel_manager_id: [
          {
            required: true,
            message: "请选择品牌经理",
            trigger: "change",
          },
        ],
        brand_id: [
          {
            required: true,
            message: "请选择品牌",
            trigger: "change",
          },
        ],
        survey_site: [
          {
            required: true,
            message: "请选择是否勘场",
            trigger: "change",
          },
        ],
        survey_date: [
          {
            required: true,
            message: "请选择约定勘场日期",
            trigger: "change",
          },
        ],
        designer_id: [
          {
            required: true,
            message: "请选择设计师",
            trigger: "change",
          },
        ],
        template_id: [
          {
            required: true,
            message: "请选择验收模板",
            trigger: "change",
          },
        ],
      },
      designerList: [], //设计师列表
      cityList: [], //省市区数据
      userList: [], //客户列表
      channelManagerList: [], //品牌经理列表
      brandList: [], //品牌列表
      addLoading: false,
      addShow: false,
      otherBrand: "",
      receivingAccountList: [],
      projectTypeList: [],//门店类型列表
      accountManagerAdminList: [],//客户经理
    };
  },
  watch: {
    addDialogVisible() {
      if (this.addDialogVisible) {
        this.userInfo = getUserInfo();//操作者信息
        this.getAdminList();//设计师列表
        this.getAreaList();//省市区
        this.getUserList();//客户列表
        this.getChannel_managerList();//品牌经理列表
        this.getCompanyList();//收款账户列表
        this.accountManagerAdminListFunc();//客户经理
        // 其他品牌
        if (this.addData.brand_id == 0) {
          console.log("其他品牌", this.addData.brand_name);
          this.otherBrand = this.addData.brand_name;
        }
        // 修改数据（更新时）
        if (JSON.stringify(this.addData) != "{}") {
          for (let key in this.addData) {
            if (this.addData.hasOwnProperty(key)) { // 确保key是对象自身的属性
              if (!this.addData[key]) {
                this.addData[key] = '';
              }
            }
          }
          this.addFormInline = this.addData;
        }
        this.addShow = this.addDialogVisible;
        this.$nextTick(() => {
          this.getBrandList();//品牌列表
          this.$refs["addRuleForm"].clearValidate();
        });
      } else {
        this.addFormInline = {
          store_type_id: "",
          store_type_name: "",
          project_name: "",
          project_city: [],
          address: "",
          user_id: "",
          channel_manager_id: "",
          brand_id: "",
          survey_site: 1,
          designer_id: "",
          template_id: "",
          survey_date: "",
          receiving_account_id: "",
          construction_type: 1
        };
        this.$refs["addRuleForm"].resetFields();
        this.$refs["addRuleForm"].clearValidate();
        this.$nextTick(() => {
          this.addShow = this.addDialogVisible;
        });
      }
    },
  },
  computed: {},
  mounted() { },
  methods: {
    // 客户经理列表
    accountManagerAdminListFunc() {
      adminApi.getAdminList({
        page: 1,
        num: 999,
        identity: 1,
        position_id_arr: [2]
      }).then(res => {
        console.log(res, "客户经理列表")
        if (res.code == 200) {
          this.accountManagerAdminList = res.data.list;
        }
      })
    },
    // 收款账户列表
    getCompanyList() {
      companyApi
        .getCompanyList({
          page: 1,
          num: 999,
          account_type: 1,
        })
        .then((res) => {
          console.log(res, "收款账户列表");
          if (res.code == 200) {
            this.receivingAccountList = res.data.list;
          }
        })
        .catch((err) => { });
    },
    // 省市区
    getAreaList() {
      commonApi.getAreaList().then((res) => {
        console.log(res, "省市区");
        if (res.code == 200) {
          this.cityList = res.data;
        }
      });
    },
    // 品牌列表
    getBrandList() {
      let { template_id, store_type_id, brand_id } = this.addFormInline;
      let store_template_id = Number(store_type_id + '' + template_id);
      brandApi
        .getBrandList({
          page: 1,
          num: 9999,
          keyword: "",
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
            // 处理模板跟类型数据(修改时)
            if (this.addFormInline.id) {
              let brandIndex = res.data.list.findIndex(item => {
                return brand_id == item.id
              })
              if (brandIndex == -1) return;
              res.data.list[brandIndex].store_list.forEach(item => {
                item.value = Number(item.store_type_id + '' + item.template_id),
                  item.label = item.store_type_name + '(' + item.template_name + ')';
              })
              this.projectTypeList = res.data.list[brandIndex].store_list;
              this.addFormInline.store_template_id = store_template_id;
              this.$nextTick(() => {
                this.$refs["addRuleForm"].clearValidate();
              })
            }
          }
        })
        .catch(() => { });
    },
    // 设计师列表
    getAdminList() {
      var obj = {
        page: 1,
        num: 9999,
        keyword: "",
        province_id: "",
        city_id: "",
        county_id: "",
        identity: 1,
        position_id_arr: [3],
      };
      adminApi
        .getAdminList(obj)
        .then((res) => {
          console.log(res, "设计师列表");
          if (res.code == 200) {
            this.designerList = res.data.list;
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        })
        .catch((err) => { });
    },
    // 客户列表
    getUserList() {
      var obj = {
        page: 1,
        num: 9999,
        keyword: "",
        province_id: "",
        city_id: "",
        county_id: "",
        identity: 4,
        position_id_arr: [],
      };
      adminApi
        .getUserList(obj)
        .then((res) => {
          console.log(res, "客户列表");
          if (res.code == 200) {
            this.userList = res.data.list;
            if (this.addData.user_id) {
              let index = res.data.list.findIndex((item) => {
                return item.id == this.addData.user_id;
              });
              this.addFormInline.customer_name = res.data.list[index].name;
              this.addFormInline.customer_phone = res.data.list[index].phone;
            }
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        })
        .catch((err) => { });
    },
    // 品牌经理列表
    getChannel_managerList() {
      var obj = {
        page: 1,
        num: 9999,
        keyword: "",
        province_id: "",
        city_id: "",
        county_id: "",
        identity: 3,
        position_id_arr: [],
      };
      adminApi
        .getAdminList(obj)
        .then((res) => {
          console.log(res, "品牌经理列表");
          if (res.code == 200) {
            this.channelManagerList = res.data.list;
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        })
        .catch((err) => { });
    },
    // 选择事件
    selectChangeFunc(e) {
      let index = 0;
      // if (!e.$event) return;
      switch (e.type) {
        case "user": //客户
          let userList = this.userList;
          index = userList.findIndex((item) => {
            return item.id == e.$event;
          });
          this.addFormInline.customer_name = userList[index].name;
          this.addFormInline.customer_phone = userList[index].phone;
          break;
        case "channel_manager": //品牌经理
          let channelManagerList = this.channelManagerList;
          index = channelManagerList.findIndex((item) => {
            return item.id == e.$event;
          });
          console.log(index, "index");
          this.addFormInline.channel_manager_name =
            channelManagerList[index].name;
          break;
        case "brand": //品牌
          let brandList = this.brandList;
          index = brandList.findIndex((item) => {
            return item.id == e.$event;
          });
          if (index != -1) {
            console.log(brandList[index])
            brandList[index].store_list.forEach(item => {
              item.value = Number(item.store_type_id + '' + item.template_id),
                item.label = item.store_type_name + '(' + item.template_name + ')';
            })
            this.projectTypeList = brandList[index].store_list;
            this.addFormInline.brand_name = brandList[index].name;
          }
          this.addFormInline.template_id = "";
          this.addFormInline.template_name = "";
          this.addFormInline.store_type_id = "";
          this.addFormInline.template_name = "";
          break;
        case "designer": //设计师
          let designerList = this.designerList;
          index = designerList.findIndex((item) => {
            return item.id == e.$event;
          });
          this.addFormInline.designer_name = designerList[index].name;
          break;
        case "store_type_name": //项目类型，门店类型
          let projectTypeList = this.projectTypeList;//装修类型
          index = projectTypeList.findIndex(item => {
            return item.value == e.$event;
          })
          if (index != -1) {
            this.addFormInline.store_type_id = projectTypeList[index].store_type_id;
            this.addFormInline.store_type_name = projectTypeList[index].store_type_name;
            this.addFormInline.template_id = projectTypeList[index].template_id;
            this.addFormInline.template_name = projectTypeList[index].template_name;
          } else {
            this.addFormInline.store_type_id = '';
            this.addFormInline.store_type_name = '';
            this.addFormInline.template_id = '';
            this.addFormInline.template_name = '';
          }
          break;
        case "account_manager_id": //客户经理
          let accountManagerAdminList = this.accountManagerAdminList;//客户经理
          index = accountManagerAdminList.findIndex(item => {
            return item.id == e.$event;
          })
          this.addFormInline.account_manager_name = accountManagerAdminList[index].account_manager_name;
          break;
        default:
      }
    },
    // 关闭添加项目弹窗
    cancelFunc() {
      this.$emit("cancelFunc", false);
    },
    // 添加项目
    addSubmit(formName) {
      let addFormInline = this.addFormInline;
      let obj = {
        account_manager_id: addFormInline.account_manager_id || '',
        account_manager_name: addFormInline.account_manager_name || '',

        project_id: addFormInline.id || '',
        store_type_id: addFormInline.store_type_id,
        store_type_name: addFormInline.store_type_name,
        project_name: addFormInline.project_name,
        project_number: "",
        user_id: addFormInline.user_id,
        customer_name: addFormInline.customer_name,
        customer_phone: addFormInline.customer_phone,
        province_id: addFormInline.project_city[0],
        city_id: addFormInline.project_city[1],
        county_id: addFormInline.project_city[2],
        address: addFormInline.address,
        brand_id: addFormInline.brand_id,
        brand_name: addFormInline.brand_name,
        survey_site: addFormInline.survey_site,
        channel_manager_id: addFormInline.channel_manager_id,
        channel_manager_name: addFormInline.channel_manager_name,
        designer_id: addFormInline.designer_id,
        designer_name: addFormInline.designer_name || "",
        template_id: addFormInline.template_id,
        template_name: addFormInline.template_name,
        survey_date: addFormInline.survey_date,
        receiving_account_id: addFormInline.receiving_account_id,
        construction_type: addFormInline.construction_type,
        remark: "",
      };
      console.log(obj, '参数');
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (obj.project_id) {
            this.updProject(obj);
            return;
          }
          this.addProject(obj);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加项目接口请求
    addProject(data) {
      this.addLoading = true;
      projectApi
        .addProject(data)
        .then((res) => {
          console.log(res, "添加项目");
          this.addLoading = false;
          if (res.code == 200) {
            this.$emit("addProjectSuccess", true);
          }
          this.$message({
            type: res.code == 200 ? "success" : "warning",
            message: res.message,
          });
        })
        .catch((err) => {
          this.addLoading = false;
          this.$message({
            type: "warning",
            message: err.message,
          });
        });
    },
    // 修改项目详情接口请求
    updProject(data) {
      this.addLoading = true;
      projectApi
        .updProject(data)
        .then((res) => {
          console.log(res, "修改项目");
          this.addLoading = false;
          if (res.code == 200) {
            this.$emit("addProjectSuccess", true);
          }
          this.$message({
            type: res.code == 200 ? "success" : "warning",
            message: res.message,
          });
        })
        .catch((err) => {
          this.addLoading = false;
          this.$message({
            type: "warning",
            message: err.message,
          });
        });
    },
    // 去添加品牌
    goToAddBrankFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/brandList' //arr[index].path,
      });
      return;
      let menu = store.getters.permission_routes;
      let arr = [];
      menu.forEach((element) => {
        if (element.children) {
          arr = [...arr, ...element.children];
        }
      });
      let index = arr.findIndex((item) => {
        return item.meta.title == "品牌列表";
      });
      if (index == -1) {
        this.$message.warning("暂无权限");
        return;
      }
      this.$router.push({
        path: arr[index].path,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>